package com.ruoyi.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.ruoyi.domain.*;
import com.ruoyi.service.IErpPurchaseRequestManagementService;
import com.ruoyi.service.OrderDetailBomImpl;
import com.ruoyi.service.impl.ErpSupplierManagementServiceImpl;
import com.ruoyi.service.impl.PurchaseDetailBomImpl;
import io.netty.util.internal.NativeLibraryLoader;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.service.IErpPurchaseOrderManagementService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 采购单管理Controller
 *
 * @author ruoyi
 * @date 2025-07-17
 */
@RestController
@RequestMapping("/erp-orders/orders")
public class ErpPurchaseOrderManagementController extends BaseController {
    @Autowired
    private IErpPurchaseOrderManagementService erpPurchaseOrderManagementService;
    @Autowired
    private IErpPurchaseRequestManagementService erpPurchaseRequestManagementService;
    @Autowired
    private PurchaseDetailBomImpl purchaseDetailBom;
    @Autowired
    private ErpSupplierManagementServiceImpl supplierManagementService;
    @Autowired
    private ErpSupplierManagementServiceImpl erpSupplierManagementServiceImpl;
    @Autowired
    private OrderDetailBomImpl orderDetailBom;


    /**
     * 查询采购单管理列表
     */
    @PreAuthorize("@ss.hasPermi('erp-orders:orders:list')")
    @GetMapping("/list")
    public TableDataInfo list(ErpPurchaseOrderManagement erpPurchaseOrderManagement) {
        startPage();
        List<ErpPurchaseOrderManagement> list = erpPurchaseOrderManagementService.selectErpPurchaseOrderManagementList(erpPurchaseOrderManagement);
        System.err.println("list = " + list);
        return getDataTable(list);
    }

    /**
     * 导出采购单管理列表
     */
    @PreAuthorize("@ss.hasPermi('erp-orders:orders:export')")
    @Log(title = "采购单管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ErpPurchaseOrderManagement erpPurchaseOrderManagement) {
        List<ErpPurchaseOrderManagement> list = erpPurchaseOrderManagementService.selectErpPurchaseOrderManagementList(erpPurchaseOrderManagement);
        ExcelUtil<ErpPurchaseOrderManagement> util = new ExcelUtil<ErpPurchaseOrderManagement>(ErpPurchaseOrderManagement.class);
        util.exportExcel(response, list, "采购单管理数据");
    }

    /**
     * 获取采购单管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('erp-orders:orders:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return success(erpPurchaseOrderManagementService.selectErpPurchaseOrderManagementById(id));
    }

    /**
     * 新增请购单管理
     */


    /**
     * 修改采购单管理
     */
    @PreAuthorize("@ss.hasPermi('erp-orders:orders:edit')")
    @Log(title = "采购单管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ErpPurchaseOrderManagement erpPurchaseOrderManagement) {
        return toAjax(erpPurchaseOrderManagementService.updateErpPurchaseOrderManagement(erpPurchaseOrderManagement));
    }

    /**
     * 删除采购单管理
     */
    @PreAuthorize("@ss.hasPermi('erp-orders:orders:remove')")
    @Log(title = "采购单管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(erpPurchaseOrderManagementService.deleteErpPurchaseOrderManagementByIds(ids));
    }

    /**
     * 获取请购单中已审核部分转化为采购单
     */
    @Log(title = "采购单管理")
    @PostMapping("/order")
    public TableDataInfo findAllByIdAndPurchaseOrderNo()
//        将请购单加入到采购单中
    {
        List<ErpPurchaseOrderPurchaseVO> erpPurchaseOrderPurchaseVOS = erpPurchaseOrderManagementService.insertErpPurchase();

        if (erpPurchaseOrderPurchaseVOS != null) {
            startPage();
            return getDataTable(erpPurchaseOrderPurchaseVOS);

        }
        return getDataTable(erpPurchaseOrderPurchaseVOS);
    }

    /**
     * 获取采购单管理的物料信息
     */
    @PostMapping(value = "/order/{id}")
    public AjaxResult orderwuliaoId(@PathVariable("id") int id) {
        return success(erpPurchaseOrderManagementService.orderwuliaoId(id));
    }
    /*采购的物料细目*/
//    @Log(title = "选择后加入采购单物料细目之中")
//    @PostMapping("/order/bom/{id}")
//    public Map<String, Integer> findAllByIdBom(@PathVariable("id") int id) {
//        erpPurchaseOrderManagementService.findAllByIdBom(id);
////        将请购单加入到采购单中
//        {
//            Map map = new HashMap();
//            if (erpPurchaseOrderManagementService.insertErpPurchase()) {
//                map.put("code", 200);
//                return map;
//            }
//            map.put("code", 0);
//            return map;
//        }
//
//    }


    //以下均为流程操作

    /*审核供应商管理 审核*/
    @PostMapping("/audit")
    public AjaxResult updateaudit(@RequestParam("id") int id, @RequestParam("opinion") String opinion, @RequestParam("choice") int choice) {
        ErpPurchaseOrderManagement erpSupplierManagement = new ErpPurchaseOrderManagement();
        erpSupplierManagement.setOpinion(opinion);
        erpSupplierManagement.setChoice(choice);
        erpSupplierManagement.setId(id);
        Map<String, Integer> i = erpPurchaseOrderManagementService.updateAudit(erpSupplierManagement);
        //添加审批记录

        if (i.get("审核成功？") > 0) {
            return AjaxResult.success(i);
        } else {
            return AjaxResult.error("审核失败");
        }
    }


    /*审核供应商管理 审核提交*/
    @PostMapping("/submit/{id}")
    public AjaxResult submit(@PathVariable("id") int id) {
        Map<String, Integer> i = erpPurchaseOrderManagementService.submit(id);
        if (i.get("提交成功？") > 0) {
            return AjaxResult.success(i);
        } else {
            return AjaxResult.error("提交失败");

        }
    }


    /*强制终止*/
    @PostMapping("/end")
    public Map<String, String> forceCompleteProcess(@RequestParam("ids") List<Integer> ids, @RequestParam("reasona") String reasona) {
        Map<String, String> end = erpPurchaseOrderManagementService.end(ids, reasona);
        return end;
    }
//

    /*审核供应商管理 弃审*/
    @PostMapping("/reject/{id}")
    public AjaxResult rejectaudit( @PathVariable("id") int id) {
        int i = erpPurchaseOrderManagementService.rejectaudit( id);
        if (i > 0) {
            return AjaxResult.success("驳回成功");
        } else {
            return AjaxResult.error("驳回失败");
        }
    }



//
//
//
//    /*请购管理 保存*/
//    @PostMapping("/saveUpdateaudit")
//    public AjaxResult saveAudit(@RequestBody ErpPurchaseRequestManagement erpPurchaseRequestManagement) {
//        System.out.println(erpPurchaseRequestManagement);
//        if (ObjectUtils.isEmpty(erpPurchaseRequestManagement)) {
//            System.out.println("发送过来对象为空");
//        }
//        System.out.println("开始保存");
//        boolean save = erpPurchaseRequestManagementService.save(erpPurchaseRequestManagement);
//        if (save) {
//            return AjaxResult.success("保存成功");
//        }
//        return AjaxResult.error("保存失败");
//    }
//
//

    /*审核供应商管理 关联待采购 细目表*/
    @PostMapping("/orderdetail/{id}")
    public Object orderDetail(@PathVariable("id") int id) {
        List<ErpPurchaseOrderPurchaseVO> erpPurchaseOrderPurchaseVOS = erpPurchaseOrderManagementService.orderDetail(id);
        System.err.println("erpPurchaseOrderPurchaseVOS = " + erpPurchaseOrderPurchaseVOS);

        if (erpPurchaseOrderPurchaseVOS!=null) { // Java 11
            System.out.println("查询成功");
            return erpPurchaseOrderPurchaseVOS;
        }else {

            System.err.println("查询失败");
            System.err.println("purchaseDetail = " + erpPurchaseOrderPurchaseVOS);
            List<PurchaseDetailBom> purchaseDetailBoms = erpPurchaseRequestManagementService.PurchaseDetail(id);
            return purchaseDetailBoms;
        }



    }

//
//
//
//    }
//
//
//
//    /* 查看详细物料 发送过来的id为采购细目表中联合物料表的id*/
//    @PostMapping("/detail/{id}")
//    public List<PurchaseDetailBom> selectPurchaseDetailid(@PathVariable("id") int id) {
//        List< PurchaseDetailBom> purchaseDetail = erpPurchaseRequestManagementService.PurchaseDetailId(id);
//        Optional<List<PurchaseDetailBom>> optionalStr = Optional.ofNullable(purchaseDetail);
//        if (optionalStr.isEmpty()) { // Java 11
//            System.err.println("查询失败");
//            System.err.println("purchaseDetail = " + purchaseDetail);
//        }else {
//            System.out.println("查询成功");
//        }
//        return purchaseDetail;
//
//
//
//    }

//
//     * 新增可选择物料 发送主键和他的物料id 加入到中间表中*/

        //查看审核的记录
    @GetMapping("/jilu/{id}")
    public List<ApprovalRecord> approvalrecord(@PathVariable("id") Integer id) {
        System.err.println("id = " + id);
        List<ApprovalRecord> purchaseDetail = erpPurchaseRequestManagementService.jilu(id);
        Optional<List<ApprovalRecord>> optionalStr = Optional.ofNullable(purchaseDetail);
        if (optionalStr.isEmpty()) { // Java 11
            System.err.println("查询失败");
            System.err.println("purchaseDetail = " + purchaseDetail);
        }else {
            System.out.println("查询成功");
            System.err.println("purchaseDetail = " + purchaseDetail);
        }
        return purchaseDetail;



    }
//
//
//    /*
//     * 删除可选择物料*/
//    @PostMapping("/deletematerials/{id}/{wid}")
//    public int deletematerials(@PathVariable("id") int id ,@PathVariable("wid") int wid) {
//        int  materials = erpPurchaseRequestManagementService.deleteDetailId(id,wid);
//        if (materials!=0) { // Java 11
//            System.err.println("删除成功");
//            return materials;
//        }else {
//            System.out.println("删除失败");
//            return materials;
//        }
//
//
//
//
//    }
    //类只是容器是内容的 里面装入内容才叫对象 只有对象才有内容
    @GetMapping("/selectsupper")
    public List<ErpSupplierManagement> selectsupper() {
        List<ErpSupplierManagement> erpSupplierManagements = erpSupplierManagementServiceImpl.getsupper();
        Optional<List<ErpSupplierManagement>> optionalStr = Optional.ofNullable(erpSupplierManagements);
        if (optionalStr.isEmpty()) { // Java 11
            System.err.println("查询失败");
            System.err.println("erpSupplierManagements = " + erpSupplierManagements);
        } else {
            System.out.println("查询成功");
            System.err.println("purchaseDetail = " + erpSupplierManagements);
        }
        return erpSupplierManagements;


    }


    //     * 查询可选择物料*/
    @GetMapping("/selectmaterials")
    public List<PurchaseDetailBom> selectmaterials() {
        List<PurchaseDetailBom> materials = erpPurchaseRequestManagementService.selectmaterials();
        Optional<List<PurchaseDetailBom>> optionalStr = Optional.ofNullable(materials);
        if (optionalStr.isEmpty()) { // Java 11
            System.err.println("查询失败");
            System.err.println("purchaseDetail = " + materials);
        } else {
            System.out.println("查询成功");
            System.err.println("purchaseDetail = " + materials);
        }
        return materials;


    }


    @PostMapping("/addmaterials")
    public Map<String, Integer> addmaterials(@RequestParam("ids") List<PurchaseDetailBom> ids, @RequestParam("key") int Key) {
        boolean materials = purchaseDetailBom.addmaterials(ids, Key);
        Map<String, Integer> map = new HashMap<>();
        if (materials) { // Java 11
            System.err.println("新增成功");
            System.err.println("purchaseDetail = " + materials);
            map.put("msg", 200);

        } else {
            System.out.println("新增失败");
            map.put("msg", 0);
        }
        return map;

    }


    //    @PreAuthorize("@ss.hasPermi('purchase:purchase:add')")
    @Log(title = "请购单管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public Map<String, Object> add(@RequestBody PurchaseRequest2 request) {
        ErpPurchaseOrderManagement erpPurchaseRequestManagement = request.getErpPurchaseOrderManagement();
        System.err.println("erpPurchaseOrderRequestManagement = " + erpPurchaseRequestManagement);
        List<OrderDetailBom2> purchaseRequestItemList = request.getPurchaseRequestItemList();
        System.err.println("erpPurchaseRequestManagement = " + erpPurchaseRequestManagement);
        Map map = erpPurchaseOrderManagementService.insertErpPurchaseRequestManagement(erpPurchaseRequestManagement);
        Integer purchaseId = erpPurchaseRequestManagement.getXzid();
        System.err.println("purchaseId = " + purchaseId);
        orderDetailBom.addmaterials(purchaseRequestItemList, purchaseId);
        return map;
    }
    /*发布订单*/
    @PostMapping("/fabu")
    public Map<String, String> handleorder(@RequestParam("ids") List<Integer> ids) {
        Map<String, String> end = erpPurchaseOrderManagementService.handleorder(ids);

        return end;
    }






    @Log(title = "采购单管理", businessType = BusinessType.INSERT)
    @PostMapping("/updatesw")
    public int updatesw(@RequestBody PurchaseRequest2 request) {
        ErpPurchaseOrderManagement erpPurchaseRequestManagement = request.getErpPurchaseOrderManagement();
        System.err.println("erpPurchaseOrderRequestManagement = " + erpPurchaseRequestManagement);
        List<OrderDetailBom2> purchaseRequestItemList = request.getPurchaseRequestItemList();
        System.err.println("erpPurchaseRequestManagement = " + erpPurchaseRequestManagement);
       int updatesw= erpPurchaseOrderManagementService.updatesw(erpPurchaseRequestManagement);
        Integer purchaseId = erpPurchaseRequestManagement.getId();
        System.err.println("purchaseId = " + purchaseId);
        System.err.println("purchaseId = " + purchaseId);
        orderDetailBom.addmaterials(purchaseRequestItemList, purchaseId);
        return updatesw;
    }







    /**
     * 导出请购单管理列表
     */
    @PreAuthorize("@ss.hasPermi('purchase:purchase:export')")
    @Log(title = "采购单管理", businessType = BusinessType.EXPORT)
    @PostMapping("/wuliao/export")
    public void wuliaoexport(HttpServletResponse response, @RequestParam("id") int id) {
        List<ErpPurchaseOrderPurchaseVO> erpPurchaseOrderPurchaseVOS = erpPurchaseOrderManagementService.orderDetail(id);
        System.err.println("erpPurchaseOrderPurchaseVOS = " + erpPurchaseOrderPurchaseVOS);

        Optional<List<ErpPurchaseOrderPurchaseVO>> optionalStr = Optional.ofNullable(erpPurchaseOrderPurchaseVOS);
        if (optionalStr.isEmpty()) { // Java 11
            System.out.println("查询成功");
            ExcelUtil<ErpPurchaseOrderPurchaseVO> util = new ExcelUtil<ErpPurchaseOrderPurchaseVO>(ErpPurchaseOrderPurchaseVO.class);
            util.exportExcel(response, erpPurchaseOrderPurchaseVOS, "请购单管理数据");
        }else {
try {


    System.err.println("查询失败");
    System.err.println("purchaseDetail = " + erpPurchaseOrderPurchaseVOS);
    List<PurchaseDetailBom> purchaseDetailBoms = erpPurchaseRequestManagementService.PurchaseDetail(id);
    ExcelUtil<PurchaseDetailBom> util = new ExcelUtil<PurchaseDetailBom>(PurchaseDetailBom.class);
    util.exportExcel(response, purchaseDetailBoms, "采购单管理数据");
}catch (Exception e){
    e.getStackTrace();
}
        }





    }
}
